<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Nabeel2
 * Date: 16/05/13
 * Time: 05:32 م
 * To change this template use File | Settings | File Templates.
 */
class informer
{
    public static function insert_request($post)
    {
        $con = util::open_connection();
        $email = mysql_real_escape_string($post['email']);
        $page_url = mysql_real_escape_string($post['page_url']);
        $search_term = mysql_real_escape_string($post['search_term']);
        $tab = mysql_real_escape_string($post['tab']);


        mysql_query("INSERT INTO `requests` (request_date, email, page_url, search_term, tab) values (NOW(), '$email', '$page_url', '$search_term', '$tab')");
        util::close_connection($con);
    }

    public static function get_requests()
    {
        $con = util::open_connection();
        $data = array();
/*
        $data['Fast+Furious+6+2013']['original_search_term'] = "Fast Furious 6 (2013)";
        $data['Fast+Furious+6+2013']['page_url'] = "http://trendx.info/transform?movieid=1234567";
        $data['Fast+Furious+6+2013']['tabs']['dvdrip']['emails']['ali512@gmail.com'] = "ali512@gmail.com";
        $data['Fast+Furious+6+2013']['tabs']['dvdrip']['emails']['udnweb@gmail.com'] = "udnweb@gmail.com";
        $data['Fast+Furious+6+2013']['tabs']['720p']['emails']['udnweb@gmail.com'] = "udnweb@gmail.com";
        $data['Fast+Furious+6+2013']['tabs']['720p']['emails']['ali512@gmail.com'] = "ali512@gmail.com";
        $data['Fast+Furious+6+2013']['tabs']['1080p']['emails']['udnweb@gmail.com'] = "udnweb@gmail.com";
        return $data;
*/
        $result = mysql_query("SELECT * FROM  `requests` WHERE served =0 AND search_term <>  '' AND (check_date IS NULL OR DATEDIFF( NOW( ) , check_date ) >3)");

        while ($row = mysql_fetch_array($result))
        {
            $tmp = $row['search_term'];

            $row['search_term'] = preg_replace("/[^A-Za-z0-9 ]/", '', $row['search_term']);
            $row['search_term'] = preg_replace('/\s+/', ' ',$row['search_term']);
            $row['search_term'] = str_replace(' ', '+', $row['search_term']);

            $data[$row['search_term']]['original_search_term'] = $tmp;
            $data[$row['search_term']]['tabs'][$row['tab']]['emails'][$row['email']] = $row['email'];
            $data[$row['search_term']]['page_url'] = $row['page_url'];
        }

        util::close_connection($con);
        return $data;
    }
    //logic
    public static function inform()
    {
        set_time_limit (0);
        $requests = informer::get_requests();
		//print_r($requests);
		//exit();
        //$i=0;
        foreach($requests as $search_term => $request_data)
        {
            //print_r($request_data).'<br />';
            //if($i>5) break;

            $request_tabs = ""; //string to send to check_availability function e.g. ("-dvdrip-720p-1080p")
            foreach($request_data['tabs'] as $tab => $obj)
                $request_tabs .= "-".$tab;

            $found_tabs = informer::check_availability($search_term, $request_tabs); //found_tabs is an array of tab names i.e. ['dvdrip', '720p', '1080p']

            foreach($found_tabs as $found_tab)
            {
                informer::send_email($request_data['original_search_term'], $found_tab, $request_data['page_url'], $request_data['tabs'][$found_tab]['emails']);
                informer::update_requests($request_data['original_search_term'], $found_tab, 1);
            }
			informer::update_last_check($request_data['original_search_term']);
            //$i++;
        }
    }

    public static function check_availability($search_term, $tabs)
    {
        util::log_to_file("checking $search_term in $tabs");
        $providers = array("isohunt", "tpb", "filesTube", "ahashare", "kat", "subscene");

        $bad_keywords = "R5-R6-DVDScr-CAM-TS-Telesync-CAMRip-telecine-hdcam";

        $results = array();//what we found
        $requested_tabs = $tabs;

        foreach ($providers as $provider)
        {
            if(strlen(str_replace("-","",$tabs)) != 0) //if there are still any yet to find tabs
            {
                $found_tabs = download::downloadp($provider, $search_term, $tabs, true, true, $bad_keywords);

                if($found_tabs)
                {
                    foreach ($found_tabs as $key=>$value)
                    {
                        $tabs = str_replace($key, "", $tabs);
                        if(strpos($requested_tabs, $key) !== false)
                            $results[$key] = $key;
                    }
                }
            }
            else
            {
                //we already found all so break the loop
                break;
            }
        }

        return $results;
    }
    public static function update_requests($search_term, $tab, $served)
    {
        $con = util::open_connection();
        $search_term = mysql_real_escape_string($search_term);
        $tab = mysql_real_escape_string($tab);


        mysql_query("update `requests` set served = 1,check_date = NOW(), available_date = NOW() where search_term = '$search_term' and tab='$tab'");
        util::close_connection($con);

    }
    public static function update_last_check($search_term)
    {
        $con = util::open_connection();
        $search_term = mysql_real_escape_string($search_term);


        mysql_query("update `requests` set check_date = NOW() where search_term = '$search_term'");
        util::close_connection($con);

    }
    public static function send_email($search_term, $tab, $page_url, $emails)
    {
        //                if($request_data['tabs'][$found_tab]['emails'])
        //foreach($request_data['tabs'][$found_tab]['emails'] as $email)
		
		
		ob_start(); ?>
		<html>
		<head>
		  <title>UDNMovies Informer</title>
		</head>
		<body>
			<p>Dear Movie Fan,</p>
			<p>You recently requested to be notified when <b><?=$search_term?></b> becomes available in <b><?=$tab?><b> format.</p>
			<p>We are happy to inform you that it is now available and you can download it by visiting <a href="<?=$page_url?>&inform=1"><?=$search_term?> Torrent Download - UDNMovies</a></p>
			<p>You can also check out our latest additions by visiting <a href="http://trendx.info">UDNMovies homepage.</a> </p>
			<p>Your feedback is welcome so Do not forget to <a href="http://facebook.com/udnmovies">LIKE us on facebook</a> and share with us your best comments and suggestions!";</p>
			<p>UDNMovies Team</p>
		</body>
		</html>
		<?php $message = ob_get_clean();
		
		
        if($emails)
            foreach($emails as $email)
            {
                //echo "found $search_term in $tab, visit $page_url to download. Sending this to $email. </br>";                
				informer::email($email, "Your Requested Movie $search_term in $tab is Available for Download", $message);
            }
    }
    public static function email($to, $subject, $message)
    {
        $email = 'info@trendx.info';


		// To send HTML mail, the Content-type header must be set
		$headers  = 'MIME-Version: 1.0' . "\r\n";
		$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

		// Additional headers
        $headers  .= "From: UDNMovies <" . $email . ">\r\n";

		// Mail it
		mail($to, $subject, $message, $headers);
		
		
        ini_set('sendmail_from', $email);

        mail($to, $subject, $message, $headers);//echo 'email sent 2';
        util::log_to_file("sent email to $to about $subject");
    }
}
